package cn.information.view;

import cn.information.bean.User;
import cn.information.dao.UserDao;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class LoginUI extends JFrame {
    UserDao userDao = new UserDao();
    List<User> users = userDao.findAll();
    JTextField txtUname = new JTextField(10);
    JPasswordField txtPassword = new JPasswordField(10);

    public LoginUI() {
        setTitle("登录页面");
        setBounds(100, 100, 400, 300);
        setLayout(new BorderLayout());

        getContentPane().setBackground(new Color(240, 245, 255)); // 浅蓝色

        JPanel panelUp = new JPanel();
        JLabel panelCenter = new JLabel();
        JPanel panelDown = new JPanel();

        add(panelUp, BorderLayout.NORTH);
        add(panelCenter, BorderLayout.CENTER);
        add(panelDown, BorderLayout.SOUTH);

        // 设置各面板背景颜色
        panelUp.setBackground(new Color(240, 245, 255));
        panelCenter.setBackground(new Color(240, 245, 255));
        panelDown.setBackground(new Color(240, 245, 255));

        panelUp.add(new JLabel("用户名："));
        panelUp.add(txtUname);
        panelUp.add(new JLabel("密码："));
        panelUp.add(txtPassword);

        JButton btnLogin = new JButton("登录");
        panelDown.add(btnLogin);
        btnLogin.addActionListener(new LoginActionListener());

        btnLogin.addActionListener( e -> {
        });
        JButton btnCancel = new JButton("取消");
        panelDown.add(btnCancel);
        btnCancel.addActionListener( e -> {
            //弹窗提醒用户，是否退出
            int result = JOptionPane.showConfirmDialog(null, "是否退出？", "提示", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                System.exit(0);
            }
        });
    }

    class LoginActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            for(User user : users) {
                if (user.getUname().equals(txtUname.getText()) && txtPassword.getText().equals(user.getPaswrd())) {
                    JOptionPane.showMessageDialog(null, "登录成功");
                    setVisible(false);
                    dispose();
                    new MainUI(user).setVisible(true);
                }else {
                    JOptionPane.showMessageDialog(null, "用户名或密码错误");
                }
                break;
            }
        }
    }
    public static void main(String[] args) {
        new LoginUI().setVisible(true);
    }
}
